package com.lisp.algorithm.tailrecursion;

import com.lisp.algorithm.util.SortUtil;

/**
 * In computer science, a tail call is a subroutine call performed as the final action of a procedure.
 * If the target of a tail is the same subroutine, the subroutine is said to be tail-recursive, 
 * which is a special case of direct recursion. Tail recursion (or tail-end recursion) is particularly useful, 
 * and often easy to handle in implementations.
 *
 * Tail calls can be implemented without adding a new stack frame to the call stack. Most of the frame of the 
 * current procedure is no longer needed, and can be replaced by the frame of the tail call, 
 * modified as appropriate (similar to overlay for processes, but for function calls). 
 * The program can then jump to the called subroutine. Producing such code instead of a standard call sequence 
 * is called tail call elimination or tail call optimization. Tail call elimination allows procedure calls in 
 * tail position to be implemented as efficiently as goto statements, thus allowing efficient structured programming. 
 * 
* @author liushuai21
 *
 */
public class QuickSort {
    
    public static void main(String[] args) {        
        SortUtil.test(QuickSort::sort);
    }
    
    public static void sort(int a[]) {
        sortSpaceOptimized(a, 0, a.length);
    }

    /** 最直观版本 */
    public static void sort(int a[], int start, int end) {
        if(start < end-1) {
            int p = partition(a, start, end);
            sort(a, start, p+1);
            sort(a, p+1, end);
        }
    }
    
    /** 尾调用优化版本  如果数组已经是有序的, 需要O(n) stack frame */
    public static void sortSpaceOptimized1(int a[], int start, int end) {
        while(start < end-1) {
            int p = partition(a, start, end);
            sortSpaceOptimized(a, start, p+1); // 递归左半边
            start = p+1;                // 迭代右半边
        }
    }
    
    /** 尾调用优化版本  最坏情况下，也只需要O(lg(n)) stack frame */
    public static void sortSpaceOptimized(int a[], int start, int end) {
        while(start < end-1) {
            int p = partition(a, start, end);
            if(p < (start+end)/2) {
                sortSpaceOptimized(a, start, p+1); // 递归较短的左半边
                start = p+1;                // 迭代右半边
            } else {
                sortSpaceOptimized(a, p+1, end); // 递归较短的右半边
                end = p+1;                  // 迭代左半边
            }
        }
    }
    
    public static int partition(int a[], int start, int end) {
        int pivot = a[start];
        int i = start-1;
        int j = end;
        
        while(true) {
            do {
                i++;
            } while(a[i] < pivot);
            
            do {
                j--;
            } while(a[j] > pivot);
            
            if(i < j) {
                SortUtil.swap(a, i, j);
            } else {
                return j;
            }
        }
    }
}
